package
{
	import flash.display.Sprite;
	
	public class Test extends Sprite
	{
		public function Test()
		{
			super();
			var xml:XML = 
				<foo xmlns:bar="bar">
					<bar:foo bar:foo="whatever" spam="egg"/>
					<moo:foo bar:foo="something else"/>
				</foo>;
			trace(this.replaceNamespace(xml, 
				xml.bar::foo.namespace(), 
				new Namespace("baz")));
		}
		
		private function replaceNamespace(xml:XML, nsA:Namespace, nsB:Namespace):XML
		{
			var result:XML;
			var spaces:Array = xml.inScopeNamespaces();
			var needsMoreReplace:Boolean;
			var childOrAttribute:XML;
			
			if (xml.namespace() == nsA)
				result = <{nsB.prefix}:{xml.localName()} xmlns:{nsB.prefix}={nsB.uri}/>;
			else result = <{xml.name()}/>;
			
			for each (var space:Namespace in spaces)
			{
				if (space == nsA)
				{
					needsMoreReplace = true;
					break;
				}
			}
			if (needsMoreReplace)
			{
				for each (childOrAttribute in xml.*)
					result.* += this.replaceNamespace(childOrAttribute, nsA, nsB);
				for each (childOrAttribute in xml.@*)
				{
					if (childOrAttribute.namespace() == nsA)
					{
						result.addNamespace(nsB);
						result["@" + nsB.prefix + ":" + 
							childOrAttribute.localName()] = xml[childOrAttribute];
					}
					else result[childOrAttribute.name()] = xml[childOrAttribute];
				}
			}
			return result;
		}
	}
}